# -*- coding:utf-8 -*-
# @FileName  :main.py
# @Time      :2023/11/14 20:21
# @Author    :lin

import re
import datetime
import random
import threading
import requests

from decorate import *
from try_decorate import *
from write_log import *


def sleep_random(start: float = 0.5, end: float = 1):
    sleep = random.uniform(start, end)
    if sleep > 1:
        print_log(f"本次休眠{sleep}秒", datetime.datetime.now().replace(microsecond=0), "\n")
    time.sleep(sleep)


@task_retry()
def res_list():
    url = "https://stuworkpc.sandau.edu.cn/api/supwisdom-stuwork-secendclass/actSubject/getActivitiesBySubjectId?size=100"
    payload = {}
    headers = headers_list[random.randint(0, len(headers_list) - 1)]
    _response = requests.request("GET", url, headers=headers, data=payload)
    return _response


@task_retry()
def res_detail(_publishId):
    url = f"https://stuworkpc.sandau.edu.cn/api/supwisdom-stuwork-secendclass/actpublish/getPublishDetailById?publishId={_publishId}"
    payload = {}
    headers = headers_list[random.randint(0, len(headers_list) - 1)]
    _response = requests.request("GET", url, headers=headers, data=payload)
    return _response


@task_retry()
def res_actApply(_headers, _studentId, _publishId):
    url = "https://stuworkpc.sandau.edu.cn/api/supwisdom-stuwork-secendclass/v1/api/secondclass/actsign/actApply"
    payload = '{"studentId":"' + _studentId + '","publishId":"' + _publishId + '"}'
    headers = _headers
    response = requests.request("POST", url, headers=headers, data=payload)
    print_log(response.text)
    return response


@debug
def do_apply(_mail_to, _name, _studentId, _headers, _subject, _publishId):
    res = res_actApply(_headers, _studentId, _publishId)
    _content_text = _name + "\n" + datetime.datetime.now().replace(microsecond=0).strftime("%Y%m%d %X") + "\n"
    if not res.text:
        _content_text += "报名失败"
    res_json = res.json()
    if not res_json:
        _content_text += "报名失败"
    else:
        _content_text += res_json["msg"] if res_json["msg"] else "msg为空"
    print_log(_content_text)
    mail.send_mail(_mail_to, _subject, _content_text)


@debug
def do(_publishId):
    detail_res = res_detail(_publishId)
    while not detail_res.text:
        sleep_random()
        detail_res = res_detail(_publishId)
    detail_json = detail_res.json()  # json化
    alreadyEntryNum = detail_json["data"]["alreadyEntryNum"]  # 已报名人数
    alreadyEntryNum = int(alreadyEntryNum) if alreadyEntryNum else 0  # 格式化成int用于判断人数
    applyLimit = detail_json["data"]["applyLimit"]  # 报名上限
    applyLimit = int(applyLimit) if applyLimit else 0  # 格式化成int用于判断人数
    applyTypeName = detail_json["data"]["applyTypeName"]  # 报名类型
    if _publishId == "1729349645940637697":  # 调试
        print(end='')
    if applyTypeName != "限额制" or (alreadyEntryNum >= applyLimit != 0):  # 判断是否是要监控的程序
        publishId_list.append(_publishId)
        return
    activityName = detail_json["data"]["activityName"]  # 活动名字
    gradeHourRule = detail_json["data"]["gradeHourRule"]  # 学分
    activityStartTime = detail_json["data"]["activityStartTime"]  # 活动开始时间
    activityEndTime = detail_json["data"]["activityEndTime"]  # 活动结束时间
    signAddress = detail_json["data"]["signAddress"]  # 活动地址
    limitCampusName = detail_json["data"]["limitCampusName"]  # 活动参与范围
    updateTime = detail_json["data"]["updateTime"]  # 更新时间
    createTime = detail_json["data"]["createTime"]  # 创建时间
    if not updateTime:
        updateTime = createTime
    if not updateTime:
        return
    if limitCampusName == '2嘉善校区' or activityName in noActivityName or "献血" in activityName:
        publishId_list.append(_publishId)
        return

    time_update = datetime.datetime.strptime(updateTime, '%Y-%m-%d %H:%M:%S')  # 把字符串转换成时间
    time_now = datetime.datetime.now().replace(microsecond=0)
    seconds = (time_now - time_update).seconds
    if seconds <= 60:
        seconds_list.append(60 - seconds)
        result = re.findall(r"\d+", gradeHourRule)
        result = result if result else [0]
        _subject = "二课活动名字：" + activityName
        if int(result[0]) >= 2:  # 设置学分自动抢
            for user in Users:
                if user.studentId:
                    # do_apply(host, user.name, user.studentId, user.headers, _subject, _publishId)
                    do_apply(user.mail_to, user.name, user.studentId, user.headers, _subject, _publishId)
        _content_text = f'''
            可获得：{gradeHourRule}\n
            活动时间：{activityStartTime} ~ {activityEndTime}\n
            已报名/报名上限：{alreadyEntryNum} / {applyLimit}\n
            活动地址：{signAddress}\n
            活动参与范围：{limitCampusName}\n
        '''
        # mail.send_mail(host, _subject, _content_text)
        mail.send_mail(mail_to, _subject, _content_text)
        print_log(datetime.datetime.now().replace(microsecond=0))
        print_log(_subject)
        print_log(_content_text)


@debug
def main():
    while True:
        seconds_list.clear()  # 清空休眠时间list防止同一个活动发送两次邮件
        start_time = datetime.datetime.now().replace(microsecond=0)
        list_res = res_list()
        while not list_res.text:
            time.sleep(1)
            list_res = res_list()
        list_json = list_res.json()
        if (
                not list_json["data"] or
                not list_json["data"]["subjectTypeVOList"] or
                not list_json["data"]["subjectTypeVOList"]["records"]
        ):
            continue
        records = list_json["data"]["subjectTypeVOList"]["records"]
        names = []
        thread_list = []
        for item in records:
            publishId = item['publishId']
            names.append(item['name'])
            if publishId not in publishId_list:
                # do(publishId)
                temp = threading.Thread(target=do, args=(publishId,))
                thread_list.append(temp)
                temp.start()
                sleep_random(0, 0.5)
        for item in thread_list:
            item.join()  # 等待全部子线程结束
        end_time = datetime.datetime.now().replace(microsecond=0)
        print_log("本次运行耗时：", end_time - start_time, "秒")
        print_log("程序运行中...", datetime.datetime.now().replace(microsecond=0))
        print_log(names, len(names), seconds_list)
        if seconds_list:
            sleep = max(seconds_list) + 1
            print_log(f"本次休眠{sleep}秒", datetime.datetime.now().replace(microsecond=0), "\n")
            time.sleep(sleep)
        else:
            sleep_random(15, 45)


if __name__ == '__main__':
    seconds_list = []
    publishId_list = []
    main()
# https://stuworkpc.sandau.edu.cn/#/secondclass/activityCenter/activityCenter
